package com.szewec.ps.ui.road.facilities.traffic;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.databinding.ActivityRoadTrafficInvestigationTaskBinding;
import com.szewec.ps.model.MyPoint;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.traffic.RoadTrafficCount;
import com.szewec.ps.model.road.traffic.RoadTrafficInvestigationTask;
import com.szewec.ps.model.road.traffic.RoadTrafficInvestigationTaskDTO;
import com.szewec.ps.model.task.SurveyObjectModel;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.common.SelectCoordinatesActivity;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.RollUtils;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.GsonUtil;
import com.szewec.ps.util.ListUtil;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.okhttp.OkHttp;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class RoadTrafficInvestigationTaskActivity extends BaseActivity {
    private ActivityRoadTrafficInvestigationTaskBinding binding;

    // 通行类型
    private List<String> trafficTypeDict = new ArrayList<>();
    // 模式
    private List<String> patternDict = new ArrayList<>();
    // 方向
    private List<String> directionDict = new ArrayList<>();
    // 方向多选框的数据
    private List<String> directionList = new ArrayList<>();

    // 用于区分新增还是修改还是详情展示
    private String modeFlag;
    private ViewModeValue viewModeValue;
    // 路段交通量调查任务实体类
    private RoadTrafficInvestigationTask roadTrafficInvestigationTask = new RoadTrafficInvestigationTask();
    // 调查对象
    private SurveyObjectModel surveyObjectModel;
    // 坐标
    private List<MyPoint> pointList;

    private static final String WEST_TO_EAST = "西向东";
    private static final String EAST_TO_WEST = "东向西";
    private static final String NORTH_TO_SOUTH = "北向南";
    private static final String SOUTH_TO_NORTH = "南向北";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_traffic_investigation_task);
        ButterKnife.bind(this);

        initData();
        selectRoadSectionTrafficTask();
        initTitleBar();
    }

    private void initData() {
        // 初始化字典
        trafficTypeDict = Enums.RoadSectionTrafficTypeEnum.getEnumValueList();
        patternDict = Enums.TrafficPatternTypeEnum.getEnumValueList();
        directionDict = Enums.RoadSectionDirectionEnum.getEnumValueList();

        // 获取intent中的数据
        PresentValue<SurveyObjectModel> presentValue = (PresentValue<SurveyObjectModel>) getIntent().getSerializableExtra(Constants.EXTRA_KEY.ROAD_TRAFFIC_INVESTIGATION_TASK);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        // 获取调查对象
        surveyObjectModel = presentValue.getT();
        Log.i("路段交通量调查 调查对象", JSONObject.toJSONString(surveyObjectModel));
    }

    /**
     * 查询路段交通量数据
     */
    private void selectRoadSectionTrafficTask() {
        OkHttp.get("/tpms-plan-service/api/road-section-task/" + surveyObjectModel.getId(), null, null, (result -> {
            Log.i("查询路段设施调查任务result", result);
            RoadTrafficInvestigationTaskDTO dto = GsonUtil.GsonToBean(result, RoadTrafficInvestigationTaskDTO.class);

            roadTrafficInvestigationTask = dto.getData() == null ? new RoadTrafficInvestigationTask() : dto.getData();
            // 设置页面内容
            initView();
        }));
    }

    private void initView() {
        // 道路名称
        String surveyName = StringUtils.isEmpty(roadTrafficInvestigationTask.getSurveyName()) ?
                surveyObjectModel.getSurveyName() : roadTrafficInvestigationTask.getSurveyName();

        // 获取路段交通量的坐标信息
        String coordinate = roadTrafficInvestigationTask.getCoordinate();
        // 如果路段交通量调查任务坐标信息为空，使用调查对象的坐标信息
        coordinate = StringUtils.isEmpty(coordinate) ? surveyObjectModel.getCoordinate() : coordinate;
        // 转换为坐标对象
        pointList = JSONArray.parseArray(coordinate, MyPoint.class);

        // 处理车流计数对象
        String trafficCount = roadTrafficInvestigationTask.getTrafficCount();
        if (StringUtils.isNotEmpty(trafficCount)) {
            // 转换车流对象数据
            List<RoadTrafficCount> trafficCountList = JSONArray.parseArray(trafficCount, RoadTrafficCount.class);
            if (CollectionUtils.isNotEmpty(trafficCountList)) {
                for (RoadTrafficCount roadTrafficCount : trafficCountList) {
                    // 设置方向的默认选中的值
                    directionList.add(roadTrafficCount.getDirection());
                    initTrafficCount(roadTrafficCount);
                }
            }
        }

        binding.surveyName.setValue(surveyName);
        binding.locationEdit.setText("查看路段");
        binding.trafficType.setValue(Enums.RoadSectionTrafficTypeEnum.getValueByKey(roadTrafficInvestigationTask.getTrafficType()));
        binding.pattern.setValue(Enums.RoadSectionTrafficTypeEnum.getValueByKey(roadTrafficInvestigationTask.getPattern()));
        binding.roadName.setValue(roadTrafficInvestigationTask.getRoadName());
        binding.direction.setValue(CommonUtils.listToStringCommaSplicing(directionList));
    }

    // 设置车流计数详情界面的展示隐藏
    private void initTrafficCount(RoadTrafficCount roadTrafficCount) {
        Integer minibus = roadTrafficCount.getMinibus();
        Integer mediumSizedCar = roadTrafficCount.getMediumSizedCar();
        Integer largeVehicle = roadTrafficCount.getLargeVehicle();
        Integer hingeCar = roadTrafficCount.getHingeCar();
        switch (roadTrafficCount.getDirection()) {
            // 西向东
            case WEST_TO_EAST:
                binding.llWestToEastCount.setVisibility(View.VISIBLE);
                binding.westToEastMinibus.setValue(minibus);
                binding.westToEastMediumSizedCar.setValue(mediumSizedCar);
                binding.westToEastLargeVehicle.setValue(largeVehicle);
                binding.westToEastHingeCar.setValue(hingeCar);
                break;
            // 东向西
            case EAST_TO_WEST:
                binding.llEastToWestCount.setVisibility(View.VISIBLE);
                binding.eastToWestMinibus.setValue(minibus);
                binding.eastToWestMediumSizedCar.setValue(mediumSizedCar);
                binding.eastToWestLargeVehicle.setValue(largeVehicle);
                binding.eastToWestHingeCar.setValue(hingeCar);
                break;
            // 南向北
            case NORTH_TO_SOUTH:
                binding.llNorthToSouthCount.setVisibility(View.VISIBLE);
                binding.northToSouthMinibus.setValue(minibus);
                binding.northToSouthMediumSizedCar.setValue(mediumSizedCar);
                binding.northToSouthLargeVehicle.setValue(largeVehicle);
                binding.northToSouthHingeCar.setValue(hingeCar);
                break;
            // 北向南
            case SOUTH_TO_NORTH:
                binding.llSouthToNorthCount.setVisibility(View.VISIBLE);
                binding.southToNorthMinibus.setValue(minibus);
                binding.southToNorthMediumSizedCar.setValue(mediumSizedCar);
                binding.southToNorthLargeVehicle.setValue(largeVehicle);
                binding.southToNorthHingeCar.setValue(hingeCar);
                break;
        }
    }

    private void initTitleBar() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);

        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    // 保存数据
    private void appendOrModifyData() {
        // 获取页面的数据
        setRoadTrafficInvestigationTask();

        Log.i("路段交通量调查 paramData", JSONObject.toJSONString(roadTrafficInvestigationTask));
        String url = "";
        // ID不为空 视为编辑
        if (StringUtils.isNotEmpty(roadTrafficInvestigationTask.getId())) {
            url = "/tpms-plan-service/api/road-section-task/update";
        } else {
            url = "/tpms-plan-service/api/road-section-task/save";
        }
        OkHttp.post(url, roadTrafficInvestigationTask, (result -> {
            JSONObject jsonObject = JSONObject.parseObject(result);
            Log.i(TAG, "create roadTrafficInvestigationTask result is：" + jsonObject);

            String code = (String) jsonObject.get("code");
            assert code != null;

            if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))) {
                Object msg = jsonObject.get("msg");
                BamToast.showText(this, "请求错误：" + msg);
                return;
            }

            BamToast.showText(this, "保存成功");
            setResult(RESULT_OK, new Intent());
            finish();
        }));
    }

    // 组装保存的参数
    private void setRoadTrafficInvestigationTask() {
        roadTrafficInvestigationTask.setSurveyObjectId(surveyObjectModel.getId());
        roadTrafficInvestigationTask.setSurveyName(binding.surveyName.getStringValue());
        roadTrafficInvestigationTask.setCoordinate(JSONArray.toJSONString(pointList));
        roadTrafficInvestigationTask.setTrafficType(Enums.RoadSectionTrafficTypeEnum.getKeyByValue(binding.trafficType.getStringValue()));
        roadTrafficInvestigationTask.setPattern(Enums.TrafficPatternTypeEnum.getKeyByValue(binding.pattern.getStringValue()));
        roadTrafficInvestigationTask.setRoadName(binding.roadName.getStringValue());
        roadTrafficInvestigationTask.setTrafficCount(setRoadTrafficCount());
    }

    // 组装车流计数对象
    private String setRoadTrafficCount() {
        List<RoadTrafficCount> roadTrafficCountList = new ArrayList<>();

        // 获取各个方向车流计数的值
        // 西向东
        if (View.VISIBLE == binding.llWestToEastCount.getVisibility()) {
            RoadTrafficCount roadTrafficCount = new RoadTrafficCount();
            roadTrafficCount.setDirection(WEST_TO_EAST);
            roadTrafficCount.setMinibus(binding.westToEastMinibus.getIntValue());
            roadTrafficCount.setMediumSizedCar(binding.westToEastMediumSizedCar.getIntValue());
            roadTrafficCount.setLargeVehicle(binding.westToEastLargeVehicle.getIntValue());
            roadTrafficCount.setHingeCar(binding.westToEastHingeCar.getIntValue());
            roadTrafficCountList.add(roadTrafficCount);
        }
        // 东向西
        if (View.VISIBLE == binding.llEastToWestCount.getVisibility()) {
            RoadTrafficCount roadTrafficCount = new RoadTrafficCount();
            roadTrafficCount.setDirection(EAST_TO_WEST);
            roadTrafficCount.setMinibus(binding.eastToWestMinibus.getIntValue());
            roadTrafficCount.setMediumSizedCar(binding.eastToWestMediumSizedCar.getIntValue());
            roadTrafficCount.setLargeVehicle(binding.eastToWestLargeVehicle.getIntValue());
            roadTrafficCount.setHingeCar(binding.eastToWestHingeCar.getIntValue());
            roadTrafficCountList.add(roadTrafficCount);
        }
        // 南向北
        if (View.VISIBLE == binding.llNorthToSouthCount.getVisibility()) {
            RoadTrafficCount roadTrafficCount = new RoadTrafficCount();
            roadTrafficCount.setDirection(NORTH_TO_SOUTH);
            roadTrafficCount.setMinibus(binding.northToSouthMinibus.getIntValue());
            roadTrafficCount.setMediumSizedCar(binding.northToSouthMediumSizedCar.getIntValue());
            roadTrafficCount.setLargeVehicle(binding.northToSouthLargeVehicle.getIntValue());
            roadTrafficCount.setHingeCar(binding.northToSouthHingeCar.getIntValue());
            roadTrafficCountList.add(roadTrafficCount);
        }
        // 北向南
        if (View.VISIBLE == binding.llSouthToNorthCount.getVisibility()) {
            RoadTrafficCount roadTrafficCount = new RoadTrafficCount();
            roadTrafficCount.setDirection(SOUTH_TO_NORTH);
            roadTrafficCount.setMinibus(binding.southToNorthMinibus.getIntValue());
            roadTrafficCount.setMediumSizedCar(binding.southToNorthMediumSizedCar.getIntValue());
            roadTrafficCount.setLargeVehicle(binding.southToNorthLargeVehicle.getIntValue());
            roadTrafficCount.setHingeCar(binding.southToNorthHingeCar.getIntValue());
            roadTrafficCountList.add(roadTrafficCount);
        }

        return JSONObject.toJSONString(roadTrafficCountList);
    }

    @OnClick({R.id.trafficType, R.id.pattern, R.id.direction, R.id.locationEdit})
    public void onViewClicked(View view) {
        //隐藏系统软键盘
        TextViewUtil.closeKeyboard(this);
        switch (view.getId()) {
            case R.id.trafficType:
                RollUtil.alertBottomWheelOption(this, trafficTypeDict, binding.trafficType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.trafficType.setValue(trafficTypeDict.get(index));
                    }
                });
                break;
            case R.id.pattern:
                RollUtil.alertBottomWheelOption(this, patternDict, binding.pattern.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.pattern.setValue(patternDict.get(index));
                    }
                });
                break;
            case R.id.direction:
                RollUtils.showCheck(this, directionDict, directionList, list -> {
                    directionList = (List<String>) list;
                    binding.direction.setValue(CommonUtils.listToStringCommaSplicing(list));
                    // 根据选择的方向动态展示车流计数详细数据
                    showORHideDirection();
                });
                break;
            // 点击坐标
            case R.id.locationEdit:
                String point = null;
                Intent intent = new Intent(this, SelectCoordinatesActivity.class);
                if (ListUtil.isNotEmpty(pointList)) {
                    point = JSONArray.toJSONString(pointList);
                    binding.locationEdit.setText("查看路段");
                }
                PresentValue<String> presentValue = new PresentValue<>(Constants.SELECT_COOR_FLAG.SELECT_COOR, point);
                intent.putExtra(Constants.EXTRA_KEY.SELECT_COOR, presentValue);
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), v -> {
                    if (v.getData() != null) {
                        pointList = JSONObject.parseArray((v.getData().getStringExtra(Constants.EXTRA_KEY.SELECT_COOR)), MyPoint.class);
                    }
                }).launch(intent);
                break;
        }
    }

    // 根据选择的方向动态展示车流计数界面
    private void showORHideDirection() {
        // 西向东
        if (directionList.contains(WEST_TO_EAST)) {
            binding.llWestToEastCount.setVisibility(View.VISIBLE);
        } else {
            binding.llWestToEastCount.setVisibility(View.GONE);
        }
        // 东向西
        if (directionList.contains(EAST_TO_WEST)) {
            binding.llEastToWestCount.setVisibility(View.VISIBLE);
        } else {
            binding.llEastToWestCount.setVisibility(View.GONE);
        }
        // 北向南
        if (directionList.contains(SOUTH_TO_NORTH)) {
            binding.llSouthToNorthCount.setVisibility(View.VISIBLE);
        } else {
            binding.llSouthToNorthCount.setVisibility(View.GONE);
        }
        // 南向北
        if (directionList.contains(NORTH_TO_SOUTH)) {
            binding.llNorthToSouthCount.setVisibility(View.VISIBLE);
        } else {
            binding.llNorthToSouthCount.setVisibility(View.GONE);
        }
    }
}